import {
  Col,
  Form,
  Drawer,
  Input,
  Row,
  Upload,
  Button,
  message,
  Select,
  Typography,
} from "antd";
import { useForm } from "antd/lib/form/Form";
import { RcFile } from "antd/lib/upload";
import { UploadFile } from "antd/lib/upload/interface";
import { useCallback, useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { BaseUrl, urlData } from "../../../http/config";
import { addContent, updateContent } from "../../../http/content";
import { homeActions, selectAllClassify } from "../../home/home.slice";
import {
  selectedContent,
  selectIsShowSetModule,
  SetActions,
} from "../set.slice";

export const CreateModule = () => {
  const dispatch = useDispatch();
  const [form] = useForm();
  const isVisible = useSelector(selectIsShowSetModule);

  const content = useSelector(selectedContent);
  
  const classifys = useSelector(selectAllClassify)

  const [title, setTitle] = useState("");

  // 初始化
  useEffect(() => {
    setTitle(content ? "编辑内容" : "新建内容");
    form.setFieldsValue({
      ...content,
      imgUrl: content
        ? [
            {
              uid: content.id,
              name: content.imgUrl,
              status: "done",
              response: {
                path: content.imgUrl,
              },
            },
          ]
        : [],
      fileUrl: content
        ? [
            {
              uid: content.id,
              name: content.fileUrl,
              status: "done",
              response: {
                path: content.fileUrl
              },
            },
          ]
        : [],
    });
  }, [content,form]);

  const onCloseModule = useCallback(() => {
    form.resetFields();
    dispatch(SetActions.onCloseSetModule());
  }, [dispatch,form]);

  const fileBeforeUpload = useCallback((file: RcFile) => {
    const type = !!~file.name.indexOf(".md");
    if (!type) {
      message.error("此项目仅支持markdown文件");
    }
    const isLt10M = file.size / 1024 / 1024 < 10;
    if (!isLt10M) {
      message.error("文件最大10MB!");
    }
    return type;
  }, []);

  const imgBeforeUpload = useCallback((file: RcFile) => {    
    const type = file.type === "image/png" || file.type === "image/jpeg";
    if (!type) {
      message.error("此项目仅支持png/jpeg");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("文件最大2MB!");
    }
    return type&&isLt2M;
  }, []);

  const handleSubmit = useCallback(
    ({
      title,
      author,
      classify,
      tag,
      imgUrl,
      fileUrl,
      description,
      demoUrl,
    }: {
      title: string;
      author: string;
      classify: string;
      tag: string;
      imgUrl: UploadFile | UploadFile[];
      fileUrl: UploadFile | UploadFile[];
      description: string;
      demoUrl: string;
    }) => {
      const img: UploadFile = (imgUrl as UploadFile[]).length
        ? (imgUrl as UploadFile[])[0]
        : (imgUrl as UploadFile);
      const file: UploadFile = (fileUrl as UploadFile[]).length
        ? (fileUrl as UploadFile[])[0]
        : (fileUrl as UploadFile);

      if (!content) {
        addContent({
          title,
          author,
          classify,
          tag,
          imgUrl: `${BaseUrl}${img.response.path}`,
          fileUrl: file.response ?  `${BaseUrl}${file.response.path}` : "",
          description,
          demoUrl
        })
          .then((content) => {
            dispatch(homeActions.addContent(content));
            message.success("内容添加成功!");
          })
          .catch((error) => {
            dispatch(homeActions.setContent([]));
            message.error(`内容添加失败! ${error}`);
          });
      } else {
        updateContent({
          id: content?.id,
          title,
          author,
          classify,
          tag,
          imgUrl: img.response.path,
          fileUrl: file.response ? file.response.path : "",
          description,
          demoUrl,
        })
          .then((data) => {
            dispatch(homeActions.updateContent(data[0]));
            message.success("内容更新成功!");
          })
          .catch((error) => {
            dispatch(homeActions.setContent([]));
            message.error(`内容更新失败! ${error}`);
          });
      }
      onCloseModule();
    },
    [dispatch, content, onCloseModule]
  );

  return (
    <Drawer
      title={title}
      visible={isVisible}
      onClose={() => onCloseModule()}
      width={"100vw"}
    >
      <Form form={form} layout={"vertical"} onFinish={handleSubmit}>
        <Row className="rowBottom">
          <Col offset={4} span={6}>
            <Form.Item
              label="标题"
              name={"title"}
              rules={[{ required: true, message: "请输入标题" }]}
            >
              <Input />
            </Form.Item>
          </Col>
          <Col offset={4} span={6}>
            <Form.Item
              label="作者"
              name={"author"}
              rules={[{ required: true, message: "请输入作者" }]}
            >
              <Input />
            </Form.Item>
          </Col>
        </Row>

        <Row className="rowBottom">
          <Col offset={4} span={6}>
            <Form.Item
              label="分类"
              name={"classify"}
              rules={[{ required: true, message: "请输入分类" }]}
            >
              <Select
                style={{ width: 120 }}
              >
                {
                    classifys.map(i=>{
                      return (
                        <Select.Option value={i.id}>{i.name}</Select.Option>
                      )
                    })
                  
                }
              </Select>
            </Form.Item>
          </Col>
          <Col offset={4} span={6}>
            <Form.Item
              label="标签"
              name={"tag"}
              rules={[{ required: true, message: "请输入标签" }]}
            >
              <Input placeholder="标签间用英文逗号分隔" />
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col offset={4} span={6}>
            <Typography.Text type="warning">
              Markdown文件与外部链接必须填一个，两个都填则生效外部链接
            </Typography.Text>
          </Col>
        </Row>
        <Row className="rowBottom">
          <Col offset={4} span={6}>
            <Form.Item
              label="头图"
              name={"imgUrl"}
              valuePropName="fileList"
              rules={[{ required: true, message: "请上传头图" }]}
              getValueFromEvent={(e) => {
                if (Array.isArray(e)) {
                  return e;
                }
                return e && e.fileList;
              }}
            >
              <Upload
                action={`${BaseUrl}${urlData.upload}`}
                beforeUpload={imgBeforeUpload}
                maxCount={1}
              >
                <Button> 200*200</Button>
              </Upload>
            </Form.Item>
          </Col>
          <Col offset={4} span={6}>
            <Form.Item
              label="MarkDown文件"
              name={"fileUrl"}
              valuePropName="fileList"
              getValueFromEvent={(e) => {
                if (Array.isArray(e)) {
                  return e;
                }
                return e && e.fileList;
              }}
            >
              <Upload
                action={`${BaseUrl}${urlData.upload}`}
                beforeUpload={fileBeforeUpload}
                maxCount={1}
              >
                <Button>请上传内容文件</Button>
              </Upload>
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col offset={4} span={6}>
            <Form.Item
              label="外部链接"
              name={"demoUrl"}
            >
              <Input placeholder="填写外部链接地址即可" />
            </Form.Item>
          </Col>
        </Row>
        <Row className="rowBottom">
          <Col offset={4} span={16}>
            <Form.Item
              label="简介"
              name={"description"}
              rules={[{ required: true, message: "请输入简介" }]}
            >
              <Input allowClear />
            </Form.Item>
          </Col>
        </Row>
        <Row className="rowBottom">
          <Col offset={4} span={16}>
            <Button type="primary" size="large"  htmlType={"submit"}>
              提交
            </Button>
          </Col>
        </Row>
      </Form>
    </Drawer>
  );
};
